import ctypes
import os
import subprocess


def read_hosts_file():
    hosts_file_path = r"C:\Windows\System32\drivers\etc\hosts"
    result = []
    if os.path.exists(hosts_file_path):
        try:
            with open(hosts_file_path, 'r', encoding='utf-8') as file:
                for line in file:
                    line = line.strip()
                    if line and not line.startswith('#') and not line.__contains__('#'):
                        parts = line.split()
                        if len(parts) >= 2:
                            ip = parts[0]
                            hostnames = ' '.join(parts[1:])
                            result.append((ip, hostnames))
        except Exception as e:
            print(f"读取文件时出现错误: {e}")
    else:
        print(f"文件 {hosts_file_path} 不存在。")
    return result

def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False


def write_list_to_file(data_list):
    file_path = r"C:\Windows\System32\drivers\etc\hosts"
    try:
        with open(file_path, 'w') as file:
            for item in data_list:
                file.write(item + '\n')
        print(f"内容已成功写入到 {file_path} 文件中。")
    except Exception as e:
        print(f"写入 {file_path} 文件时出错: {e}")

def flush_dns_cache():
    try:
        # 执行 ipconfig /flushdns 命令
        result = subprocess.run(['ipconfig', '/flushdns'], capture_output=True, text=True, check=True)
        print("命令执行成功，输出信息如下：")
        print(result.stdout)
    except subprocess.CalledProcessError as e:
        print(f"命令执行失败，错误信息：{e.stderr}")

from selenium import webdriver  # 导入selenium的webdriver模块
from selenium.webdriver.common.by import By  # 引入By类选择器

if __name__ == "__main__":
    hosts_mappings = read_hosts_file()
    # 创建Chrome WebDriver对象
    driver = webdriver.Chrome()

    driver.implicitly_wait(6)  # 使用浏览器隐式等待3秒
    data = []
    for ip, hostnames in hosts_mappings:
        driver.get("https://tool.lu/dns/index.html")
        # 获取账号密码组件并赋值
        userInput = driver.find_element(By.XPATH,
                                        '//*[@id="bdy"]/div/div[1]/div/form/p[1]/input')
        userInput.send_keys(hostnames)
        userInput = driver.find_element(By.XPATH, '//*[@id="bdy"]/div/div[1]/div/form/p[1]/button')
        userInput.click()
        elements = driver.find_elements(By.XPATH,
                                        '//*[@id="bdy"]/div/div[1]/div/table/tbody/tr[2]/td[2]')
        if elements:
            print(f"{elements[0].text} {hostnames}")
            data.append(f"{elements[0].text} {hostnames}")
        else:
            print(f"#{ip} {hostnames}")
            data.append(f"#{ip} {hostnames}")


    write_list_to_file(data)
    flush_dns_cache()
    # print("站长之家")
    # for ip, hostnames in hosts_mappings:
    #     try:
    #         driver.get("https://whois.chinaz.com/")
    #         # 获取账号密码组件并赋值
    #         userInput = driver.find_element(By.XPATH,
    #                                         '//*[@id="keyword_search"]/div/div/input')
    #         userInput.send_keys(hostnames)
    #         userInput = driver.find_element(By.XPATH, '//*[@id="search_btn"]')
    #         userInput.click()
    #         elements = driver.find_elements(By.XPATH,
    #                                         '//*[@id="dns_info"]/div[1]/div/span/a')
    #         if elements:
    #             text = elements[0].text
    #             print(f"{text[len('[A] '):]} {hostnames}")
    #         else:
    #             print(f"#{ip} {hostnames}")
    #     except Exception as e:
    #         print(f"Error: {e}")
    #         break
    # driver.quit()

# 刷新host
# ipconfig/flushdns